package text

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
)

func NewChat(apiKey string) *Chat {
	client := &http.Client{}

	return &Chat{
		client:             client,
		apiKey:             apiKey,
		endpoint:           "https://dashscope.aliyuncs.com/compatible-mode",
		uriChatCompletions: "/v1/chat/completions",
		model:              "qwen-plus",
		modelVisual:        "qwen-vl-plus",
		modelVideo:         "qwen-vl-max-latest",
		modelLong:          "qwen-long",
	}
}

type Chat struct {
	client             *http.Client
	apiKey             string
	endpoint           string
	uriChatCompletions string
	model              string
	modelVisual        string
	modelVideo         string
	modelLong          string
}

func (r *Chat) GetUrl(url string) string {
	return fmt.Sprintf("%s%s", r.endpoint, url)
}
func (r *Chat) Chat(messages []Message) string {
	requestBody := RequestBody{
		Model:    r.model,
		Messages: messages,
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest("POST", r.GetUrl(r.uriChatCompletions), bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}

	req.Header.Set("Authorization", "Bearer "+r.apiKey)
	req.Header.Set("Content-Type", "application/json")
	resp, err := r.client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			log.Fatal(err)
		}
	}(resp.Body)

	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	return string(bodyText)
}
func request() {

}
